package cn.edu.zstu.qingzhu.qingzhushop.handler.advice;


import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    Object handleControllerException(HttpServletRequest request, Throwable ex) {

        HttpStatus status = getStatus(request);
        log.warn(ex.getMessage(), ex);
        return new ResponseBean.Builder()
                .setStatus(status.value())
                .setMsg(ex.getMessage())
                .build();
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
